const empty = () => {
}

export class CountTimer {
  constructor (config) {
    let {deadline, during, end, error, now, type = 'countDown'} = config
    this.deadline = deadline
    this.during = during || empty
    this.end = end || empty
    this.error = error || empty
    this.now = now ? new Date(now) : new Date()
    this.type = type || 'timeUpdate'
    this.init()
  }
  static friendly (t) {
    let d = Math.floor(t / 864e5)
    let h = Math.floor(t / 36e5 - d * 24)
    let m = Math.floor(t / 6e4 - d * 24 * 60 - h * 60)
    let s = Math.floor(t / 1e3 - d * 24 * 60 * 60 - h * 60 * 60 - m * 60)
    return `${d} ${h}:${m}:${s}`
  }
  init () {
    this[this.type]()
    if (this.type == 'timeUpdate') {
      this.record = +new Date(this.now)
    } else {
      this.record = new Date(this.deadline)
    }
  }
  // 倒计时
  timerDown () {
    if (this.record < this.now) {
      this.error(this.record - this.now)
    }
    if (this.record - this.now < 1000) {
      return this.end(this.record - this.now)
    }
    setTimeout(() => {
      this.record -= 1000
      // 返回开始时间和结束时间的差距
      this.during(this.record - this.now)
      this.timerDown()
    }, 1000)
  }
  // 时间自增
  timeUpdate () {
    setTimeout(() => {
      this.record += 1000
      // 返回最新日期
      this.during(this.record)
      this.timeUpdate()
    }, 1000)
  }
}
// 倒计时
